<?php

declare(strict_types=1);

namespace App\Common\Middleware;

use Base\Constants\ErrorCode;
use Base\Exception\CommonException;
use Firebase\JWT\JWT;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Utils\Context;
use Base\Middleware\Traits\Route;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;

class DashboardAuthMiddleware implements MiddlewareInterface
{
    use Route;

    public function __construct(ContainerInterface $container, ConfigInterface $config)
    {

    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $request->getHeader('blade-auth');
        $userInfo = [];
        if (isset($token[0]) && !empty($token[0])){
            try {
                list($headb64, $bodyb64, $cryptob64) = explode('.', $token[0]);
                $userInfo = (array)JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
            }catch (\Exception $e){
                throw new CommonException(ErrorCode::AUTH_FAILED,'token无效');
            }
        }else{
            throw new CommonException(ErrorCode::TOKEN_INVALID,'token为必传');
        }
        if(empty($userInfo['user_name'])){
            throw new CommonException(ErrorCode::AUTH_LOGIN_FAILED,'获取token数据失败');
        }
        if(!empty($userInfo['dept_id'])) $userInfo['dept_id'] = (int)$userInfo['dept_id'];
        if(!empty($userInfo['corp_id'])) $userInfo['corp_id'] = (int)$userInfo['corp_id'];
        if(!empty($userInfo['user_id'])) $userInfo['user_id'] = (int)$userInfo['user_id'];
        if(!empty($userInfo['tenant_id'])) $userInfo['tenant_id'] = (int)$userInfo['tenant_id'];

        $requestParsed = $request->getParsedBody();
        $request = $request->withParsedBody(array_merge($requestParsed, ['userInfo' => $userInfo]));
        return $handler->handle($request);
    }
}
